package com.app.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.mapper.UserMapper;
import com.app.model.UserModel;
import com.app.service.UserService;
import com.app.util.HttpClientUtil;
import com.app.util.WXConstant;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserModel> implements UserService {

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public UserModel wxLogin(String code, String mobileCode) throws LoginException {
        //获取手机号
        String mobile = getMobile(mobileCode);
        //获取openid
        String openid = getOpenid(code);

        if (openid == null) {
            throw new LoginException("openid为空");
        }

        //根据openid查询用户信息
        UserModel user = userMapper.getByOpenid(openid);
        if (user == null) {
            //当前是新用户，自动注册
            user = new UserModel();
            user.setOpenid(openid);
            user.setMobile(mobile);
            user.setUserName("游客");
            user.setCrtTime(LocalDateTime.now());
            userMapper.insert(user);
            return user;
        }
        user.setMobile(mobile);
        userMapper.updateById(user);
        UserModel tbUser = new UserModel();
        tbUser.setUserName(user.getUserName());
        tbUser.setOpenid(user.getOpenid());
        tbUser.setMobile(mobile);
        tbUser.setId(user.getId());
        tbUser.setFaceUrl(user.getFaceUrl());
        return tbUser;
    }

    @Override
    public UserModel getUserByMobile(String mobile1) {
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", mobile1);
        List<UserModel> userList = userMapper.selectByMap(map);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    @Override
    public int update(UserModel user) {
        return userMapper.updateById(user);
    }

    @Override
    public UserModel save(String faceUrl, String userName, String mobile) {
        UserModel userByMobile = getUserByMobile(mobile);
        userByMobile.setUserName(userName);
        userByMobile.setFaceUrl(faceUrl);
        update(userByMobile);
        return getUserByMobile(mobile);
    }

    //查头像
    @Override
    public String getFaceUrl(int userId) {
        return userMapper.getFaceUrl(userId);

    }

    @Override
    public int getCount() {
        return userMapper.getCount();
    }

    @Override
    public UserModel selectOpenid(String code) {
        String openid = getOpenid(code);
        UserModel model = new UserModel();
        model.setOpenid(openid);
        return model;
    }

    @Override
    public List<UserModel> whiteList() {
        return userMapper.whiteList();
    }

    private String getOpenid(String code) {
        //请求封装参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", WXConstant.APPID);
        map.put("secret", WXConstant.SECRET);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }

    private String getMobile(String mobileCode) {
        // 获取token
        String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", WXConstant.APPID, WXConstant.SECRET);
        JSONObject token = JSON.parseObject(HttpUtil.get(token_url));
        // 使用前端code获取手机号码 参数为json格式
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", mobileCode);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        System.out.println(httpEntity);
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
        Object body = response.getBody();
        Map<String, Object> map = new ObjectMapper().convertValue(body, Map.class);
        Object phoneInfo = map.get("phone_info");
        Map<String, Object> map1 = new ObjectMapper().convertValue(phoneInfo, Map.class);
        // 以上都是response参数的处理 最终拿到userPhone 可以进行下一步 微信登陆了
        Object phoneNumber = map1.get("phoneNumber");
        return (String) phoneNumber;
    }
}
